package com.zzyl.serve.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.Temporal;
import java.util.*;
import java.time.temporal.ChronoUnit;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.serve.domain.*;
import com.zzyl.serve.dto.CheckInApplyDto;
import com.zzyl.serve.dto.CheckInConfigDto;
import com.zzyl.serve.dto.CheckInElderDto;
import com.zzyl.serve.dto.ElderFamilyDto;
import com.zzyl.serve.mapper.*;
import com.zzyl.serve.vo.CheckInConfigVo;
import com.zzyl.serve.vo.CheckInDetailVo;
import com.zzyl.serve.vo.CheckInElderVo;
import com.zzyl.serve.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.serve.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author Huanghc
 * @date 2025-08-15
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto dto) {

        //1. 如果老人已经入住（老人身份证号已存在，且状态为1），则抛异常
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo());
        Elder elderDb = elderMapper.selectOne(elderLambdaQueryWrapper);
        if(elderDb !=null && Objects.equals(elderDb.getStatus(),1)){
            throw  new BaseException("老人已入住");
        }
        //2. 更新床位状态为“已入住”（如果床位是未入住时才允许入住）
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        if(bed.getBedStatus().equals(1)){
            throw new BaseException("床位已入住");
        }
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3. 保存老人信息
        //  将dto中老人的信息封装成Elder对象
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder);
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        List<ElderFamilyDto> familyDtos = dto.getElderFamilyDtoList();
        elder.setRemark(JSONUtil.toJsonPrettyStr(familyDtos));
        if(elderDb==null){
            elderMapper.insert(elder);
        }else {
            elder.setId(elderDb.getId());
            elderMapper.updateById(elder);
        }

        //4.新增入住信息
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        save(checkIn);

        //5.新增入住配置信息
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);

        //6.新增签约信息
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(),contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setContractName(elder.getName());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        LocalDateTime now = LocalDateTime.now();
        boolean beInForce = !now.isBefore(contract.getStartDate()) && !now.isAfter(contract.getEndDate());
        contract.setStatus(beInForce?1:0);
        contractMapper.insert(contract);




    }

    @Override

    public CheckInDetailVo detail(Long id) {

        //查询老人信息
            CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
            CheckIn checkIn = getById(id);
            Elder elder = elderMapper.selectElderById(checkIn.getElderId());
            CheckInElderVo checkInElderVo = new CheckInElderVo();
            BeanUtils.copyProperties(elder,checkInElderVo);
        // 计算年龄
        int age = Optional.ofNullable(elder.getBirthday())
                .filter(birthdayStr -> !birthdayStr.isEmpty())
                .map(LocalDate::parse)
                .map(birthday -> (int) ChronoUnit.YEARS.between(birthday, LocalDate.now()))
                .orElse(0);
        checkInElderVo.setAge(age); // 假设 CheckInElderVo 有 age 字段

            checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //查询老人家人信息
            List<ElderFamilyVo> familyVos = JSONUtil.toList(elder.getRemark(), ElderFamilyVo.class);
            checkInDetailVo.setElderFamilyVoList(familyVos);
         //查询入住配置信息,根据入住表Id查询
            CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConfigByCheckInId(checkIn.getId());
            CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
            BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
            checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
         //查询入住合同信息，根据老人表Id查询
            Contract contract = contractMapper.selectContractByElderId(elder.getId());
            checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
